<?php
namespace api\modules\v1\controllers;

use api\models\LoginForm;
use api\models\User;
use common\helpers\Helper;
use Yii;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\rest\Controller;
use common\helpers\Decrypt;
use yii\web\NotFoundHttpException;

class SiteController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['login', 'logout'],
                'rules' => [
                    [
                        'actions' => ['login'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    public function actionIndex()
    {
        echo 'PHP是世界上最好的语言！';
    }



    public function actionLogin(){
        $code          = Yii::$app->request->post('code');
        $iv            = Yii::$app->request->post('iv');
        $encryptedData = Yii::$app->request->post('encryptedData');
        $only          = Yii::$app->request->post('only');

        $appid      = 'wx250e340dfaf6223e';//小程序唯一标识   (在微信小程序管理后台获取)
        $appsecret  = 'efb5735680a47035735d91a7d985ed93';//小程序的 app secret (在微信小程序管理后台获取)
        $grant_type = "authorization_code"; //授权（必填）
        // && !$redis->exists($only)
        $testData = [
            'code' => $code,
            'iv' => $iv,
            'encryptedData' => $encryptedData,
            'only' => $only,
        ];
        file_put_contents($_SERVER['DOCUMENT_ROOT']."/login.log","post data :".json_encode($testData).PHP_EOL,FILE_APPEND);
        if($only=="wxkey"){
            $params = "appid=".$appid."&secret=".$appsecret."&js_code=".$code."&grant_type=".$grant_type;
            $url = "https://api.weixin.qq.com/sns/jscode2session?".$params;
            $res = json_decode($this->httpGet($url),true);
            if(!isset($res['session_key'])) throw new NotFoundHttpException('解析错误session_key为空');
            $sessionKey = $res['session_key'];//取出json里对应的值
            $this->only = substr(md5($res['openid']), 8, 16);
            $sessionArr = [$sessionKey];
            Yii::$app->get('redis')->set("sessionKey:".$this->only,json_encode($sessionArr));

            if(isset($res['errcode']) && $res['errcode'] == 40163) throw new NotFoundHttpException($res['errmsg']);

        }else{
            $redisRes = Yii::$app->get('cache')->get("sessionKey:".$only);
            $sessionArr = json_decode($redisRes,true);
            $sessionKey = $sessionArr[0];
        }
        $pc = new Decrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);
        if($errCode != 0) throw new NotFoundHttpException($errCode);
        $userInfo = json_decode($data,true);
        file_put_contents($_SERVER['DOCUMENT_ROOT']."/login.log","wxInfo data:".json_encode($userInfo).PHP_EOL,FILE_APPEND);
        $loginForm = [
            'name' => $userInfo['nickName'],
            'header' => $userInfo['avatarUrl'],
            'unionid' => $userInfo['unionId']
        ];
        file_put_contents($_SERVER['DOCUMENT_ROOT']."/login.log","info data:".json_encode($loginForm).PHP_EOL,FILE_APPEND);
//        $loginForm = [
//            'name' => '大胸妹',
//            'header' => 'http://img.guotuw.com/star/23104/header.jpg',
//            'unionid' => 'daxiongmeiunionid'
//        ];
        $model = new LoginForm();
        $model->load($loginForm);
        $user = $model->login();

        $result = $user->attributes;
        $result['exceed_num'] = (int)User::find()->where(['<','bet_win',$user->bet_win])->count();
        return $result ? : [];
    }

    private function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }


}
